define(function (require) {
    require('bootstrapValidator');
    require('messager');
    require('table');
    require('typeahead');
    require('doctor-data');
    require('fileinput');
    require('daterangepicker');
    require('doctor-select');
    require('moment');
    require('clockpicker');
    require('datetimepicker');
    require('iCheck');

    $.module("BASE.BDMProductionCost", function () {

        return {
            init: function () {
                this.loadData();
                this.loadEvent();
            },
            clearDatas:function () {
                var that = this;

                $("#_id").val(0);
                $('#CompanyId').val('').removeAttr('data-id');
                $('#PeriodYear').val('');
                $('#CostCenterId').val('').removeAttr('data-id').removeAttr('data-code');
                $('#AccountViewCode').val('').removeAttr('data-id');
                $('#MaterialId').val('').removeAttr('data-id').removeAttr('data-code');
                $('#StdPackQuantity').val(0);
                $('#GroupName').val('');
                $('#ProductionOrderNumber').val('');
                $('#WorkOrderCategory').val('');
                $('#ProductionDate').val('');
                $('#WorkHours').val(0);
                $('#ProductionLineNumber').val(0);
                $('#TotalWorkHours').val(0);
                $('#ProductionQuantity').val(0);
                $('#DirectMaterial').val(0);
                $('#Packaging').val(0);
                $('#ExternalProcessingFee').val(0);
                $('#LabourCost').val(0);
                $('#Wastage').val(0);
                $('#EnergyCost').val(0);
                $('#DepreciationAmortization').val(0);
                $('#AdministrativeExpenses').val(0);
                $('#RepairCharge').val(0);
                $('#SafeProductionReserve').val(0);
                $('#ExtensiveRepair').val(0);
                $('#TotalCost').val(0);
                $('#UnitCost').val(0);

                $('#fm').bootstrapValidator('resetForm', true);
                that.showDiv('main_div');
            },
            loadData: function (pageNumber, pageSize) {
                var that = this;


                let s_CompanyName = $("#s_CompanyName").val();
                let s_CostCenterCode = $("#s_CostCenterCode").val();
                let s_CostCenterName = $("#s_CostCenterName").val();
                let s_AccountViewCode = $("#s_AccountViewCode").val();
                let s_AccountViewName = $("#s_AccountViewName").val();
                let s_MaterialCode = $("#s_MaterialCode").val();
                let s_MaterialName = $("#s_MaterialName").val();

                SYS.Core.ajax({
                    url: "base/productionCost/list",
                    common: {
                        page: pageNumber ? pageNumber : 1,
                        size: pageSize ? pageSize : 20
                    },
                    data: {
                        CompanyName: s_CompanyName,
                        CostCenterCode: s_CostCenterCode,
                        CostCenterName: s_CostCenterName,
                        AccountViewCode: s_AccountViewCode,
                        AccountViewName: s_AccountViewName,
                        MaterialCode: s_MaterialCode,
                        MaterialName: s_MaterialName,
                    },
                    success: function (data) {
                        var obj = {
                            'pageNumber': data.data.extra.current_page,
                            'pageSize': data.data.extra.page_size,
                            'totalRows': data.data.extra.all_count,
                            'data': data.data.list
                        };

                        $("#myTable").bootstrapTable('destroy');
                        $('#myTable').bootstrapTable({
                            striped: true,
                            singleSelect: false,
                            showColumns: true,
                            showToggle: true,
                            pagination: true,
                            pageNumber: obj.pageNumber,
                            pageSize: obj.pageSize,
                            totalRows: obj.totalRows,
                            pageList: [20, 50, 100, 200],
                            sidePagination: 'server',
                            clickToSelect: true,
                            idField: 'id',
                            data: obj.data,
                            columns: [
                                // {field: 'checked', checkbox: true} ,
                                {field: 'Id', title: '编号', align: 'center'},
                                {field: 'CompanyName', title: '公司名称', align: 'center'},
                                {field: 'PeriodYear', title: '会计期间', align: 'center'},
                                {field: 'CostCenterCode', title: '成本Id', align: 'center'},
                                {field: 'CostCenterName', title: '成本名称', align: 'center'},
                                {field: 'AccountViewCode', title: '科目编码', align: 'center'},
                                {field: 'AccountViewName', title: '科目名称', align: 'center'},
                                {field: 'MaterialCode', title: '物料编码', align: 'center'},
                                {field: 'MaterialName', title: '物料名称', align: 'center'},
                                {field: 'StdPackQuantity', title: '标准箱规格', align: 'center'},
                                {field: 'GroupName', title: '产品分类', align: 'center'},
                                {field: 'ProductionOrderNumber', title: '生产订单号', align: 'center'},
                                {field: 'WorkOrderCategory', title: '工单类别', align: 'center'},
                                {field: 'ProductionDate', title: '生成日期', align: 'center'},
                                {field: 'WorkHours', title: '产线工时', align: 'center'},
                                {field: 'ProductionLineNumber', title: '产线人数', align: 'center'},
                                {field: 'TotalWorkHours', title: '总工时', align: 'center'},
                                {field: 'ProductionQuantity', title: '生产数量', align: 'center'},
                                {field: 'DirectMaterial', title: '直接材料', align: 'center'},
                                {field: 'Packaging', title: '包装材料', align: 'center'},
                                {field: 'ExternalProcessingFee', title: '外协加工费', align: 'center'},
                                {field: 'LabourCost', title: '人工成本', align: 'center'},
                                {field: 'Wastage', title: '物耗', align: 'center'},
                                {field: 'EnergyCost', title: '能源费', align: 'center'},
                                {field: 'DepreciationAmortization', title: '折旧摊销', align: 'center'},
                                {field: 'AdministrativeExpenses', title: '办公费', align: 'center'},
                                {field: 'RepairCharge', title: '修理费', align: 'center'},
                                {field: 'SafeProductionReserve', title: '安全生产准备金', align: 'center'},
                                {field: 'ExtensiveRepair', title: '大修理', align: 'center'},
                                {field: 'TotalCost', title: '成本总额', align: 'center'},
                                {field: 'UnitCost', title: '单位成本', align: 'center'},
                                // {
                                //     field: 'do', title: '操作', align: 'center',
                                //     formatter: function (value, row, index) {
                                //         var html = '';
                                //         html += '<a href="javascript:void(0)" onclick="BASE.BDMProductionCost.toEdit(' + row.Id + ')" class="btn btn-edit">编辑</a> | ';
                                //         html += '<a href="javascript:void(0)" onclick="BASE.BDMProductionCost.toRemove(' + row.Id + ')" class="btn btn-remove  ">删除</a>';
                                //         return html;
                                //     }
                                // }
                            ],
                            onPageChange: function(number, size){
                                that.loadData(number, size);
                            },
                            onRefreshTable: function () {
                                that.loadData();
                            },
                            onClickCell: function (field, value, row, $element) {
                            }
                        });
                    }
                });
            },
            loadEvent: function () {
                var that = this;

                // 定义编辑框form
                var $form = $("#fm");

                // 查询
                $("#search-toolbar").on('click', "#btn_search", function () {
                    that.loadData();
                }).on("keydown ", "input", function (e) {
                    if (e.keyCode == 13) {
                        that.loadData();
                    }
                });

                //批量删除
                $("#btn_deletes").on('click',function(){
                    that.toRemoves();
                });

                // 保存新增
                $("#btn_contiune_add").on('click', function () {
                    // 不用关闭当前编辑框
                    that.save();
                });

                // 新增
                $("#btn_add").on('click', function () {
                    that.clearDatas();

                    $("#btn-add-div").show();
                    $("#btn-edit-div").hide();
                    that.showDiv('edit_div');
                });

                // 绑定日期控件
                $("#ProductionDate").datetimepicker({
                    minView: "hour",
                    format: 'yyyy-mm-dd',
                    todayBtn: true,
                    language: 'zh-CN', // 汉化
                    autoclose: true    // 选择日期后自动关闭
                }).on('changeDate', function (ev) {
                    var field = $(this).attr("id");
                    $form.find("input[data-field='" + field + "']").val(ev.date.getTime());
                });

                // 关联公司
                $("#CompanyId").on('click', function () {
                    DOCTOR.Select.showCompany(this);
                });
                // 成本中心
                $("#CostCenterId").on('click', function () {
                    DOCTOR.Select.showCostCenter(this);
                });
                // 产品
                $("#MaterialId").on('click', function () {
                    DOCTOR.Select.showMaterial(this);
                });
                // 科目
                $("#AccountViewCode").on('click', function () {
                    DOCTOR.Select.showAccountView(this);
                });

                // 返回
                $(".back_list").on('click', function () {
                    that.clearDatas();

                    that.loadData();
                    that.showDiv('main_div');
                });

                $(".i-checks").iCheck({checkboxClass:"icheckbox_square-orange", radioClass:"iradio_square-orange"});
                $("#btn_import").on('click', function () {

                    $('#fm_import').bootstrapValidator('disableSubmitButtons', false);

                    $("#import_tip").html('');
                    $("#import_file").empty();
                    $("#import_file").fileinput('refresh', {
                        uploadUrl: '/base/productionCost/importData?',
                        showUploadedThumbs: false,
                        browseClass: 'btn btn-main',
                        allowedFileExtensions: ["xls", "xlsx"],
                        uploadExtraData: function(previewId, index) {   //额外参数的关键点
                            var obj = {};
                            obj.parameters = JSON.stringify({
                                common:{},
                                data: {
                                    //Id: $("#import_id").val()
                                }
                            });
                            return obj;
                        }
                    }).on('fileuploaded', function (event, data) {
                        let obj = data.response;

                        $("#import_tip").html(obj.msg);
                    });

                    that.showDiv('import_div');
                });

                //
                $('#fm').bootstrapValidator({
                    excluded: ':disabled',
                    feedbackIcons: {
                        valid: 'glyphicon glyphicon-ok',
                        invalid: 'glyphicon glyphicon-remove',
                        validating: 'glyphicon glyphicon-refresh'
                    },
                    fields: {
                        // title: {
                        //     validators: {
                        //         notEmpty: {
                        //             message: '此项必填'
                        //         }
                        //     }
                        // },
                        // WorkHours: {
                        //     validators: {
                        //         // notEmpty: {
                        //         //     message: '此项必填'
                        //         // },
                        //         regexp: {
                        //             regexp: /^[1-9]\d*$/i,
                        //             message: '格式不正确，必须大于0'
                        //         }
                        //     }
                        // }
                    }
                }).on('success.form.bv', function (e) {
                    e.preventDefault();

                    that.save();
                });

            },
            save: function () {
                var that = this;

                let id = $("#_id").val();
                let CompanyId = $('#CompanyId').attr('data-id');
                let CompanyName = $('#CompanyId').val();
                let PeriodYear = $('#PeriodYear').val();
                let CostCenterId = $('#CostCenterId').attr('data-id') || 0;
                let CostCenterCode = $('#CostCenterId').attr('data-code');
                let CostCenterName = $('#CostCenterId').val();
                let AccountViewCode = $('#AccountViewCode').attr('data-id');
                let AccountViewName = $('#AccountViewCode').val();
                let MaterialId = $('#MaterialId').attr('data-id');
                let MaterialCode = $('#MaterialId').attr('data-code');
                let MaterialName = $('#MaterialId').val();
                let StdPackQuantity = $('#StdPackQuantity').val();
                let GroupName = $('#GroupName').val();
                let ProductionOrderNumber = $('#ProductionOrderNumber').val();
                let WorkOrderCategory = $('#WorkOrderCategory').val();
                let ProductionDate = $('#ProductionDate').val();
                let WorkHours = $('#WorkHours').val();
                let ProductionLineNumber = $('#ProductionLineNumber').val();
                let TotalWorkHours = $('#TotalWorkHours').val();
                let ProductionQuantity = $('#ProductionQuantity').val();
                let DirectMaterial = $('#DirectMaterial').val();
                let Packaging = $('#Packaging').val();
                let ExternalProcessingFee = $('#ExternalProcessingFee').val();
                let LabourCost = $('#LabourCost').val();
                let Wastage = $('#Wastage').val();
                let EnergyCost = $('#EnergyCost').val();
                let DepreciationAmortization = $('#DepreciationAmortization').val();
                let AdministrativeExpenses = $('#AdministrativeExpenses').val();
                let RepairCharge = $('#RepairCharge').val();
                let SafeProductionReserve = $('#SafeProductionReserve').val();
                let ExtensiveRepair = $('#ExtensiveRepair').val();
                let TotalCost = $('#TotalCost').val();
                let UnitCost = $('#UnitCost').val();

                SYS.Core.ajax({
                    url: 'base/productionCost/save',
                    common: {},
                    data:{
                        Id: id || 0,
                        CompanyId: CompanyId,
                        CompanyName: CompanyName,
                        PeriodYear: PeriodYear,
                        CostCenterCode: CostCenterCode,
                        CostCenterName: CostCenterName,
                        AccountViewCode: AccountViewCode,
                        AccountViewName: AccountViewName,
                        MaterialCode: MaterialCode,
                        MaterialName: MaterialName,
                        StdPackQuantity: StdPackQuantity,
                        GroupName: GroupName,
                        ProductionOrderNumber: ProductionOrderNumber,
                        WorkOrderCategory: WorkOrderCategory,
                        ProductionDate: ProductionDate,
                        WorkHours: WorkHours || 0,
                        ProductionLineNumber: ProductionLineNumber,
                        TotalWorkHours: TotalWorkHours || 0,
                        ProductionQuantity: ProductionQuantity || 0,
                        DirectMaterial: DirectMaterial || 0,
                        Packaging: Packaging || 0,
                        ExternalProcessingFee: ExternalProcessingFee || 0,
                        LabourCost: LabourCost || 0,
                        Wastage: Wastage || 0,
                        EnergyCost: EnergyCost || 0,
                        DepreciationAmortization: DepreciationAmortization || 0,
                        AdministrativeExpenses: AdministrativeExpenses || 0,
                        RepairCharge: RepairCharge || 0,
                        SafeProductionReserve: SafeProductionReserve || 0,
                        ExtensiveRepair: ExtensiveRepair || 0,
                        TotalCost: TotalCost || 0,
                        UnitCost: UnitCost || 0,
                    },
                    success: function (data) {
                        if(data.code == 1) {
                            $.messager.popup(data.msg, 'success');

                            that.clearDatas();
                            that.loadData();
                            that.showDiv('main_div');
                        } else {
                            $('#fm').bootstrapValidator('disableSubmitButtons', false);
                            $.messager.popup(data.msg, 'error');
                        }
                    }
                })
            },
            toEdit: function (id) {
                var that = this;

                that.clearDatas();
                $("#btn-add-div").hide();
                $("#btn-edit-div").show();

                SYS.Core.ajax({
                    url: 'base/productionCost/detail',
                    common: {},
                    data: {
                        Id: id ? id : 0
                    },
                    success: function (data) {
                        if (data.code == 1) {
                            let obj = data.data;

                            let id = obj.Id;
                            let CompanyId = obj.CompanyId;
                            let CompanyName = obj.CompanyName;
                            let PeriodYear = obj.PeriodYear;
                            let CostCenterId = obj.CostCenterId;
                            let CostCenterCode = obj.CostCenterCode;
                            let CostCenterName = obj.CostCenterName;
                            let AccountViewCode = obj.AccountViewCode;
                            let AccountViewName = obj.AccountViewName;
                            let MaterialId = obj.MaterialId;
                            let MaterialCode = obj.MaterialCode;
                            let MaterialName = obj.MaterialName;
                            let StdPackQuantity = obj.StdPackQuantity;
                            let GroupName = obj.GroupName;
                            let ProductionOrderNumber=obj.ProductionOrderNumber;
                            let WorkOrderCategory=obj.WorkOrderCategory;
                            let ProductionDate=obj.ProductionDate;
                            let WorkHours=obj.WorkHours;
                            let ProductionLineNumber=obj.ProductionLineNumber;
                            let TotalWorkHours=obj.TotalWorkHours;
                            let ProductionQuantity=obj.ProductionQuantity;
                            let DirectMaterial=obj.DirectMaterial;
                            let Packaging=obj.Packaging;
                            let ExternalProcessingFee=obj.ExternalProcessingFee;
                            let LabourCost=obj.LabourCost;
                            let Wastage=obj.Wastage;
                            let EnergyCost=obj.EnergyCost;
                            let DepreciationAmortization=obj.DepreciationAmortization;
                            let AdministrativeExpenses=obj.AdministrativeExpenses;
                            let RepairCharge=obj.RepairCharge;
                            let SafeProductionReserve=obj.SafeProductionReserve;
                            let ExtensiveRepair=obj.ExtensiveRepair;
                            let TotalCost=obj.TotalCost;
                            let UnitCost=obj.UnitCost;

                            $("#_id").val(id);
                            $('#CompanyId').val(CompanyName).attr('data-id', CompanyId);
                            $('#PeriodYear').val(PeriodYear);
                            $('#CostCenterId').val(CostCenterName).attr('data-code',CostCenterCode);
                            $('#AccountViewCode').val(AccountViewName).attr('data-id', AccountViewCode);
                            $('#MaterialId').val(MaterialName).attr('data-code', MaterialCode);
                            $('#StdPackQuantity').val(StdPackQuantity);
                            $('#GroupName').val(GroupName);
                            $('#ProductionOrderNumber').val(ProductionOrderNumber);
                            $('#WorkOrderCategory').val(WorkOrderCategory);
                            $('#ProductionDate').val(ProductionDate);
                            $('#WorkHours').val(WorkHours);
                            $('#ProductionLineNumber').val(ProductionLineNumber);
                            $('#TotalWorkHours').val(TotalWorkHours);
                            $('#ProductionQuantity').val(ProductionQuantity);
                            $('#DirectMaterial').val(DirectMaterial);
                            $('#Packaging').val(Packaging);
                            $('#ExternalProcessingFee').val(ExternalProcessingFee);
                            $('#LabourCost').val(LabourCost);
                            $('#Wastage').val(Wastage);
                            $('#EnergyCost').val(EnergyCost);
                            $('#DepreciationAmortization').val(DepreciationAmortization);
                            $('#AdministrativeExpenses').val(AdministrativeExpenses);
                            $('#RepairCharge').val(RepairCharge);
                            $('#SafeProductionReserve').val(SafeProductionReserve);
                            $('#ExtensiveRepair').val(ExtensiveRepair);
                            $('#TotalCost').val(TotalCost);
                            $('#UnitCost').val(UnitCost);

                            that.showDiv('edit_div');
                        }
                    }
                });
            },
            showDiv: function (div) {
                var divs = ['main_div','edit_div','import_div'];
                for(var i=0; i<divs.length; i++){
                    $("#" + divs[i]).hide();
                }
                $("#" + div).show();
            }
        }
    });
    BASE.BDMProductionCost.init();
});